#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QSettings>
#include <QImage>
#include <QBuffer>
#include "settings.h"
#include "config.h"
#include "clockcontroller.h"

ClockController::ClockController(QObject *parent) : QObject(parent)
{
    _clockStatSlotModel = new ClockStatSlotModel(this);
    _clockStatCalendarModel = new ClockStatCalendarModel(this);
    _clockForm = new ClockForm();
}

ClockStatSlotModel *ClockController::clockStatSlotModel(){
    return _clockStatSlotModel;
}

ClockStatCalendarModel *ClockController::clockStatCalendarModel(){
    return _clockStatCalendarModel;
}

QString ClockController::clockUserId(){
    return _clockForm->userId;
}

void ClockController::setClockUserId(QString userId){
    _clockForm->userId = userId;
}

QString ClockController::clockPlace(){
    return _clockForm->place;
}

void ClockController::setClockPlace(QString place){
    _clockForm->place = place;
}

QString ClockController::clockFileUrl(){
    return _clockForm->fileUrl;
}

void ClockController::setClockFileUrl(QString fileUrl){
    _clockForm->fileUrl = fileUrl;
}

void ClockController::slot_statcalendar_req(QString user_id){
    QString url = API_URL+"clock/statcalendar";
    url+="?user_id="+user_id;
    QUrl qurl(url);
    QNetworkRequest req(qurl);
    _nam = new QNetworkAccessManager(this);
    connect(_nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slot_statcalendar_res(QNetworkReply*)));
    _nam->get(req);
}

void ClockController::slot_statcalendar_res(QNetworkReply * reply)
{
    QJsonValue data = get_reply_data(reply);
    if(!data.isNull()){
        QJsonObject result = data.toObject();
        QJsonArray todayClocks = result["todayClocks"].toArray();
        QJsonArray monthClocks = result["monthClocks"].toArray();

        for (int i = 0;i<monthClocks.count();i++){
            QJsonObject clock = monthClocks.at(i).toObject();
            _clockStatCalendarModel->append({
                                                clock["clock_date"].toString(),
                                                clock["status"].toDouble(),
                                            });
        }
        for (int i = 0;i<todayClocks.count();i++){
            QJsonObject clock = todayClocks.at(i).toObject();
            QString date = clock["clock_date"].toString();
            QString time = clock["clock_at"].toString();
            QString place = clock["clock_place"].toString();
            bool isClockOn = clock["behavior"].toDouble()==1;
            _clockStatSlotModel->append({date,time,place,isClockOn});
        }
    }
    reply->deleteLater();
    emit sig_req_finished();
}

void ClockController::slot_statslot_req(QString user_id){
    QString url = API_URL+"clock/statslot";
    url+="?user_id="+user_id;
    QUrl qurl(url);
    QNetworkRequest req(qurl);
    _nam = new QNetworkAccessManager(this);
    connect(_nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slot_statslot_res(QNetworkReply*)));
    _nam->get(req);
}

void ClockController::slot_statslot_res(QNetworkReply * reply)
{
    QJsonValue data = get_reply_data(reply);
    if(!data.isNull()){
        QJsonObject result = data.toObject();
        QJsonArray todayClocks = result["clocks"].toArray();
        for (int i = 0;i<todayClocks.count();i++){
            QJsonObject clock = todayClocks.at(i).toObject();
            QString date = clock["clock_date"].toString();
            QString time = clock["clock_at"].toString();
            QString place = clock["clock_place"].toString();
            bool isClockOn = clock["behavior"].toDouble()==1;
            _clockStatSlotModel->append({date,time,place,isClockOn});
        }
    }
    reply->deleteLater();
    emit sig_req_finished();
}

void ClockController::slot_stattoday_req(QString user_id){
    QString url = API_URL+"clock/stattoday";
    url+="?user_id="+user_id;
    QUrl qurl(url);
    QNetworkRequest req(qurl);
    _nam = new QNetworkAccessManager(this);
    connect(_nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slot_stattoday_res(QNetworkReply*)));
    _nam->get(req);
}

void ClockController::slot_stattoday_res(QNetworkReply * reply)
{
    QJsonValue data = get_reply_data(reply);
    if(!data.isNull()){
        QJsonObject result = data.toObject();
        QJsonArray todayClocks = result["todayClocks"].toArray();
        for (int i = 0;i<todayClocks.count();i++){
            QJsonObject clock = todayClocks.at(i).toObject();
            QString date = clock["clock_date"].toString();
            QString time = clock["clock_at"].toString();
            QString place = clock["clock_place"].toString();
            bool isClockOn = clock["behavior"].toDouble()==1;
            _clockStatSlotModel->append({date,time,place,isClockOn});
        }
    }
    reply->deleteLater();
    emit sig_req_finished();
}

void ClockController::slot_clock_req(){
    QString url = API_URL+"clock/clock";
    QUrl qurl(url);
    QNetworkRequest req(qurl);
    req.setRawHeader("content-type","application/x-www-form-urlencoded");

    QByteArray data;
    data.append("user_id="+_clockForm->userId);
    data.append("&place="+_clockForm->place);
    if(_clockForm->fileUrl != ""){
        QUrl fileUrl(_clockForm->fileUrl);
        QImage image(fileUrl.toLocalFile());
        QByteArray ba;
        QBuffer buf(&ba);
        image.save(&buf,"PNG");
        QByteArray hexed = ba.toBase64();

        buf.close();
        data.append("&file="+hexed);
    }
    _nam = new QNetworkAccessManager(this);
    connect(_nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slot_clock_res(QNetworkReply*)));
    _nam->post(req,data);
}

void ClockController::slot_clock_res(QNetworkReply * reply)
{
    QJsonValue data = get_reply_data(reply);
    reply->deleteLater();
    emit sig_req_finished();

}

QJsonValue ClockController::get_reply_data(QNetworkReply * reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        QJsonParseError jsonpe;
        QJsonDocument json = QJsonDocument::fromJson(data, &jsonpe);
        if (jsonpe.error == QJsonParseError::NoError)
        {
            if (json.isObject()) {
                QJsonObject obj = json.object();
                int code = obj["status"].toInt();
                QString msg = obj["msg"].toString();
                qDebug()<<msg;
                if (code == 1) {
                    return obj["data"];
                    emit sig_req_success();
                }else if(code == 0){
                    emit sig_req_error(msg);
                }
            }
        }
    }else {
        qDebug() << reply->error();
    }

    return 0;
}


